package library;

import java.sql.Connection;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import java.util.ArrayList;
import java.util.List;

import jdbcutil.JDBCUtil;

public class RecordingDao {
	
	Connection conn = null;
	PreparedStatement ps = null;
	
	public Integer insert(RecordingModel model) {
		String sql = "insert into test.recording(cid,name,date,status)values(?,?,?,?)";
		try {
			conn = JDBCUtil.getConnection();
			ps = conn.prepareStatement(sql);
			ps.setString(1, model.getCid());
			ps.setString(2, model.getName());
			ps.setTimestamp(3, model.getDate());	
			ps.setInt(4, model.getStatus());
			return ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(conn, ps);
		}
		return null;
	}
	
	public List<RecordingModel> selectList(RecordingModel model) {
		List<RecordingModel> list = new ArrayList<>();
		StringBuffer sql = new StringBuffer("select Cid,name,date from test.recording");
		List<Object> vals = appendWhere(sql, model);
		ResultSet rs = null;
		try {
			conn = JDBCUtil.getConnection();
			ps = conn.prepareStatement(sql.toString());
			if (vals.size() == 0) {
				rs = ps.executeQuery();
			} else {
				for (int i = 0; i < vals.size(); i++) {
					ps.setObject(i + 1, vals.get(i));		
				}
				rs = ps.executeQuery();
			}
			while (rs.next()) {
				RecordingModel mod = new RecordingModel();
				mod.setCid(rs.getString("cid"));
				mod.setName(rs.getString("name"));
				mod.setDate(rs.getTimestamp("date"));
				list.add(mod);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			JDBCUtil.close(conn, ps, rs);
		}
		return list;
	}

	private List<Object> appendWhere(StringBuffer sql, RecordingModel model) {
		sql.append(" where 1=1");
		List<Object> objs = new ArrayList<>();
		
		String cid = model.getCid();
		if (cid != null && !cid.trim().isEmpty()) {
			sql.append(" and cid = ?");
			objs.add(cid);
		}
		String name = model.getName();
		if (name != null && !name.trim().isEmpty()) {// !"".equals(code.trim())
			sql.append(" and name = ?");
			objs.add(name);
		}
		int status = model.getStatus();
		if (status != 0 ) {
			sql.append(" and status = ?");
			objs.add(status);
		}
		return objs;
	}
}
